#include "ClientSession.h"

#include <iostream>

using namespace ENE;

ClientSession::ClientSession(boost::asio::io_service& ioService)
: SocketConnection(ioService),m_resolver(ioService)
{
}

void ClientSession::connect(const std::string& host, const std::string& port, ClientSession::ConnectCallback handler)
{
	//Requete pour trouver l'adresse du serveur	
	boost::asio::ip::tcp::resolver::query query(host, port);
	boost::asio::ip::tcp::resolver::iterator iter = m_resolver.resolve(query);

	service().post(boost::bind(&ClientSession::doConnect, this, iter, handler));
}

void ClientSession::doConnect(boost::asio::ip::tcp::resolver::iterator endpoint, ClientSession::ConnectCallback handler)
{
	socket().async_connect(*endpoint,
		boost::bind(&ClientSession::handleConnect, this,
					boost::asio::placeholders::error, ++endpoint, handler));
}

void ClientSession::handleConnect(const boost::system::error_code& error,
								boost::asio::ip::tcp::resolver::iterator endpoint_iterator, 
								ClientSession::ConnectCallback handler)
{
	if (!error)
	{
		//socket().set_option(boost::asio::ip::tcp::no_delay(true));
		//Connection reussi
		handler(error);
	}
	else if (endpoint_iterator != boost::asio::ip::tcp::resolver::iterator())
	{
		//retentative de connection avec un autre adresse
		socket().async_connect(*endpoint_iterator,
			boost::bind(&ClientSession::handleConnect, this,
			boost::asio::placeholders::error, ++endpoint_iterator, handler));
	}
	else
	{
		//Connection impossible
		handler(error);
	}
}